import { formatDate } from './utils.js'
import { number2Hanz } from '@swda/utils/number/index.js'
import lang from './i18n.js';

export default class Window_SWDA_File extends Window_Selectable {
    constructor(options) {
        super(options)
        this._title = options.title || null;
        this._mode = options.mode || 'save'
        this._pageSize = 5;
        this._index = 1;
        this._maxIndex = DataManager.maxSavefiles();
        this.refresh()
    }

    numVisibleRows() {
        return 1;// !important 意味着横向菜单
    }

    maxVisibleItems() {
        return 5
    }

    normalTextColor() {
        return this.textColor(0)
    }

    //selectTextColor() {
    //    return this.normalColor()    // 黄色是 this.textColor(6)
    //}

    initialize() {
        super.initialize()
        const width = Graphics.boxWidth + 48
        const height = Graphics.boxHeight + 48
        super.initialize(-24, -24, width, height)
        this.opacity = 0;
        this.initAllParts()
        this.refresh()
        this.activate()
    }

    initAllParts() {
        const buttonSetShopBitmap = ImageManager.loadBitmap('img/system/UI/', 'ButtonSetShop');
        const [buttonWidth, buttonHeight] = [48, 48]

        // 左右按钮
        const createButton = (column, position) => {
            const x = buttonWidth * column

            const button = new Sprite_Button()
            button.bitmap = buttonSetShopBitmap
            button.setColdFrame(x, 0, buttonWidth, buttonHeight)
            button.setHotFrame(x, buttonHeight, buttonWidth, buttonHeight)
            button.setOnFrame(x, 2 * buttonHeight, buttonWidth, buttonHeight)
            button.visible = true;
            window.buttonttt = button
            button.x = position[0]
            button.y = position[1]
            return button
        }

        this._leftButton = createButton(1, [342, 555])
        this._rightButton = createButton(2, [938, 555])
        this.addChild(this._leftButton)
        this.addChild(this._rightButton)

        this._leftButton.setClickHandler(this.onButtonLeft.bind(this))
        this._rightButton.setClickHandler(this.onButtonRight.bind(this))

        // 快照
        this._snapShot = new Sprite()
        this._snapShot.x = 345
        this._snapShot.y = 95
        this._snapShot.smooth = true;
        this.addChild(this._snapShot)

        // 头像
        this._actorSprite = []
        const dataActors = $dataActors.filter(actor => actor && actor.id && actor.name)
        dataActors.forEach((actor, i) => {
            this._actorSprite[i] = { id: actor.id, sprite: new Sprite() }
            this._actorSprite[i].sprite.x = 460 + 70 * i
            this._actorSprite[i].sprite.y = 675
            this._actorSprite[i].sprite.opacity = 0;
            const bitmapName = 'head' + actor.id + ((actor.id == 1 && $gameSwitches.value(299)) ? "a" : "");
            this._actorSprite[i].sprite.bitmap = ImageManager.loadBitmap('img/system/actors/', bitmapName);
            this.addChild(this._actorSprite[i].sprite)
        })
    }

    createSubWindows() {
        this._choiceWindow = new Window_ChoiceList(this);
    }

    refresh() {
        if (this.contents) {
            this.contents.clear()
            this.drawAllItems()
        }
    }

    index() {
        return this._index;
    }

    setIndex(index) {
        if (index > this.maxIndex()) return

        this._index = index;
    }

    maxIndex() {
        return this._maxIndex;
    }

    drawItem(index) {
        const rect = this.itemRect(index)
        this.drawText(this._mode + ' ' + index, rect.x, rect.y, rect.width, 'center')
    }
    // 饕：画光标用
    itemRect(index) {
        let rect = new Rectangle();
        const maxCols = 5;
        rect.width = 100;
        rect.height = 36;
        rect.x = 390 - 10 + (index - 1) % maxCols * (rect.width) - this._scrollX;
        rect.y = 538;
        return rect;
    };


    drawAllItems() {
        for (let i = 0; i < this.maxVisibleItems(); i++) {
            this.drawItem(i)
        }
    }

    update() {
        super.update()
    }

    updateCursor() {
        if (this._leftButton && this._rightButton) {
            if (this._index <= 1) {
                this._leftButton.enable = false
            }
        }
        if (this._index < 1) {
            this._index = 1
        }
        let rect = this.itemRect(this.index());
        this.setCursorRect(rect.x, rect.y, rect.width, rect.height);
    }

    isCursorMovable() {
        return this.active;
    }

    getActiveSaveFilesIndexs() {
        const globalInfo = DataManager.loadGlobalInfo()
        let indexInfo = []
        globalInfo.forEach((info, index) => {
            if (info !== null) indexInfo.push(index)
        })

        return indexInfo
    }

    select(index) {
        this.setIndex(index)
        this._stayCount = 0;
        this.ensureCursorVisible();
        this.updateCursor();
        this.callUpdateHelp();

    }

    onButtonLeft() {
        if ((this._index - 4) <= 1) return this.playBuzzerSound();
        this.cursorPageup()
        SoundManager.playOk();
    }

    onButtonRight() {
        if ((this._index + 4) >= this._maxIndex) return this.playBuzzerSound();
        this.cursorPagedown()
        SoundManager.playOk();
    }

    cursorPageup() {
        if ((this._index - 4) <= 1) return this.playBuzzerSound();
        this.select(this._index - 5)
        this.refresh()

    }
    cursorPagedown() {
        if ((this._index + 4) >= this._maxIndex) return this.playBuzzerSound();
        this.select(this._index + 5)
        this.refresh()
    }
    cursorUp() {
        //this.cursorLeft()
    }
    cursorDown() {
        //this.cursorRight()
    }

    cursorLeft() {
        if (this._index <= 1) return this.playBuzzerSound();
        this.select(this._index - 1)
        this.refresh()
    }

    cursorRight() {
        if (this._index >= this._maxIndex) return this.playBuzzerSound();
        this.select(this._index + 1)
        this.refresh()
    }

    scrollDown() {
        this.cursorRight(true)
    }
    scrollUp() {
        this.cursorLeft(true)
    }

    drawAllItems() {
        const index = this.index()

        this.drawWindowTitle()
        this.drawSnapshot(index)
        this.drawFileId(index)
        this.drawContents(index)
    }

    drawWindowTitle() {
        if (!this._title) return ''

        const [x, y, width] = [36, 32, 64]
        this.setTitleFont();
        this.changeTextColor(this.normalTextColor())
        this.contents.fontBold = true;
        this.drawVerticalText(this._title, x, y, width, this.titleFontSize(), 'center')
        this.resetFontSettings()
    }

    drawSnapshot(index) {
        if (index < 1) return;
        const snapshot = DataManager.loadSnapShot(index)
        this._snapShot.bitmap = Bitmap.load(snapshot)
    }

    
    hasSaveFile(index){
        const savedIndexSets = this.getActiveSaveFilesIndexs()
        return savedIndexSets.includes(index)
    }

    drawFileId(index) {
        const getStart = (index, pageSize) => index - (index - 1) % pageSize;
        const [startX, startY, maxWidth] = [390, 538, 80]
        const savedIndexSets = this.getActiveSaveFilesIndexs()

        const getPageList = (index, pageSize = 5) => {
            const start = getStart(index, pageSize); // 计算页首
            return Array.from({ length: pageSize }, (_, i) => {
                return {
                    globalIndex: start + i,
                }
            })
        }

        const pageList = getPageList(index, this._pageSize)
        const getIndexColor = (isSelected, globalIndex) => {
            //if (isSelected) return this.selectTextColor()
            if (savedIndexSets.includes(globalIndex)) {
                return this.normalColor()
            }else if(this._mode == 'save'){
                return this.textColor(8)
            }else{
                return this.crisisColor()
            }
        }

        pageList.forEach((pageItem, pageItemIndex) => {
            const pageItemX = startX + 100 * pageItemIndex;
            const pageItemChineseString = number2Hanz(pageItem.globalIndex)
            const selectedCursorIndex = index - getStart(index, this._pageSize)
            const isSelected = pageItemIndex === selectedCursorIndex
            const color = getIndexColor(isSelected, pageItem.globalIndex)
            this.changeTextColor(color)
            this.drawText(pageItemChineseString, pageItemX, startY, maxWidth, 'center')
            this.resetTextColor()
        })
    }

    drawCurrencyValue(value = 0, unit, wx, wy, ww) {
        this.changeTextColor('rgba(89, 186, 142, 1)');
        this.contents.fontSize = this.smallerFontSize();
        const cx = this.usingGoldIcon(unit) ? Window_Base._iconWidth : this.textWidth(unit)
        const text = Yanfly.Util.toGroup(value);
        //this.setNumFontSize();

        this.drawText(text, cx + wx, wy, ww - cx - 4, 'right');
        this.resetFontSettings();

        if (this.usingGoldIcon(unit)) {
            this.drawIcon(Yanfly.Icon.Gold, wx, wy + 2);
        } else {
            this.changeTextColor(this.systemColor());
            this.drawText(unit, wx, wy, ww, 'right');
        }
        this.resetFontSettings();
    };

    drawContents(index) {
        if (index <= 0) return
        const info = DataManager.loadSavefileInfo(index) || {}
        const { mapName = '', timestamp = '', playtime = '', gold = 0, actors = [] } = info

        const leftLabelX = 312
        const leftContentX = 450
        const rightX = 760
        const [col1Y, col2Y, col3Y] = [580, 615, 655]
        const dater = timestamp ? formatDate(timestamp) : ''

        const drawLabel = (...args) => {
            this.changeTextColor(this.systemColor())
            this.drawText(...args)
            this.resetTextColor()
        }

        this.changeTextColor(this.normalColor());
        // mapinfo
        drawLabel(`${lang.recordPositionLabel}：`, leftLabelX, col1Y);
        this.drawText(mapName, leftContentX, col1Y);
        // time            
        drawLabel(`${lang.timeLabel}：`, leftLabelX, col2Y);
        this.drawText(playtime, leftContentX, col2Y);
        // level
        drawLabel(`${lang.levelLabel}：`, leftLabelX, col3Y);

        // 头像
        this._actorSprite.forEach(actorSprite => {
            actorSprite.sprite.opacity = 0;
        })
        this.setSmallerFont();
        actors.forEach((actor, i) => {
            const actorId = actor[0]
            const actorSprite = this._actorSprite.find(item => item.id === actorId)
            
            if (actorSprite){
                actorSprite.sprite.x = 460 + 70 * i
                actorSprite.sprite.opacity = 255;
            }
            const level = actor[1] || ''

            this.drawText(level, leftContentX + 30 + (70 * i), col3Y);
        })
        this.resetFontSettings();
        // right
        this.drawText(timestamp ? dater.getTime() : '', rightX - 6, col2Y, 200, 'right');
        this.drawText(timestamp ? dater.getDate() : '', rightX, col1Y, 200, 'right');
        // gold
        this.drawCurrencyValue(gold, TextManager.currencyUnit, rightX + 50, col3Y, 150)
    }

    drawConfirm() {
        this.changeTextColor(this.textColor(0))
        this.drawText(lang.confirmOverwrite,310, 450, this.textWidth(lang.confirmOverwrite));
        this.resetTextColor()
    }

    clearConfirm() {
        this.contents.clearRect(310-4, 450-4, this.textWidth(lang.confirmOverwrite) + 8, this.contents.fontSize + 8);
    }

    onMove() {
        const lastIndex = this.index();
        const x = this.canvasToLocalX(TouchInput.realX);
        const y = this.canvasToLocalY(TouchInput.realY);
        const hitIndex = this.hitTest(x, y);
        if (hitIndex >= 0) {
            if (TouchInput.isMoving() && this.isCursorMovable()) {
                this.select(hitIndex);
                if (this.index() !== lastIndex)
                    this.refresh();
            }
        }
        else if (CP.MouseMoveManager.CURSOR_AUTO_MOVE && this._stayCount >= CP.MouseMoveManager.AUTO_MOVE_WAIT_COUNT) {
            if (this.isCursorTop() && y < this.padding) {
                this.cursorLeft();
            } else if (this.isCursoBottom() && y >= this.height - this.padding) {
                this.cursorRight();
            }
        }

        if (this.index() !== lastIndex) {
            SoundManager.playCursor();
        }
    }

    hitTest(x, y) {
        if (this.isContentsArea(x, y)) {
            const getStart = (index, pageSize) => index - (index - 1) % pageSize;
            const cx = x - this.padding;
            const cy = y - this.padding;
            const topIndex = getStart(this.index(), this._pageSize)
            for (let i = 0; i < 5; i++) {
                const index = topIndex + i;
                if (index <= DataManager.maxSavefiles()) {
                    const rect = this.itemRect(index);
                    const right = rect.x + rect.width;
                    const bottom = rect.y + rect.height;
                    if (cx >= rect.x && cy >= rect.y && cx < right && cy < bottom) {
                        return index;
                    }
                }
            }
        }
        return -1;
    }

    isCursorTop() {
        const index = this.index();
        const getStart = (index, pageSize) => index - (index - 1) % pageSize;
        const topIndex = getStart(this.index(), this._pageSize);

        if (index == topIndex) return true;

        return false;
    };

    isCursoBottom() {
        const index = this.index();
        const getStart = (index, pageSize) => index - (index - 1) % pageSize;
        const bottomIndex = (getStart(this.index(), this._pageSize) + 4) * this.maxCols();

        if (index == bottomIndex)
            return true;

        return false;
    };
}
